package com.kkb.service.impl;

import com.kkb.bean.Role;
import com.kkb.dao.MiddleDao;
import com.kkb.dao.RoleDao;
import com.kkb.dao.impl.MiddleDaoImpl;
import com.kkb.dao.impl.RoleDaoImpl;
import com.kkb.service.RoleService;

import java.util.List;

public class RoleServiceImpl implements RoleService {
    private RoleDao roleDao=new RoleDaoImpl();
    private MiddleDao middleDao=new MiddleDaoImpl();
    @Override
    public List<Role> getRoleList(int pageIndex, int pageSize) {
        return roleDao.getRoleList(pageIndex, pageSize);
    }

    @Override
    public int total() {
        return roleDao.total();
    }

    @Override   //事务问题
    public int insertRole(String rolename, String state, String[] ids) {
        int k1=0;
        try {
            //1.新增角色表
            Role role = new Role();
            role.setRoleName(rolename);
            role.setRoleState(Integer.parseInt(state));
            int k = roleDao.insert(role);
            //2.新增中间表
            //如何获得新增数据的id?
            middleDao.insertMiddle(k,ids);
            k1=1;
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return k1;
    }

    @Override
    public Role findById(Integer roleId) {
        return roleDao.findById(roleId);
    }

    @Override
    public int update(Integer roleId, String roleName, String state, String[] ids) {
        int k=0;
        try {
            Role role = new Role();
            role.setRoleId(roleId);
            role.setRoleName(roleName);
            role.setRoleState(Integer.parseInt(state));
            roleDao.update(role);
            middleDao.deleteByRoleId(roleId);
            middleDao.insertMiddle(roleId,ids);
            k=1;
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return k;
    }

    @Override
    public int delete(Integer roleId) {
        int k=0;
        try {
            middleDao.deleteByRoleId(roleId);
            roleDao.delete(roleId);
            k=1;
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return k;
    }
}
